package mavenProject.mavenProject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import mavenProject.Model.Question;
import mavenProject.Service.AnswerService;
import mavenProject.Service.QuestionService;
import mavenProject.Service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@org.springframework.stereotype.Controller
public class HelloController{

	@Autowired
	QuestionService questionService;
	
	@Autowired
	AnswerService answerService;
	
	@Autowired
	UserService userServise;
	

	@RequestMapping("hello.html")
	public ModelAndView handleRequest(@RequestParam(required=false) Integer id) {
		
		if(id == null){
			id=1;//(int) (Math.random()*6);
		}
		Question question = questionService.getQuestion(id);		//????????????????????????????????????????????
		
		
//		int ids =  question.getIDQuestion();
//		List<Answer> answers = answerService.getAnswersByQuestId(ids);
//		List<String> answersStrings = new ArrayList<String>();
//		
//		for(int i = 0; i<answers.size();i++){
//			answersStrings.add(answers.get(i).getAnswer());
//		}
//		
		ModelAndView view  = new ModelAndView("hello");
		view.addObject("questionsObject",question);
//		view.addObject("answers",answersStrings);
		return view;
	}
	
	@RequestMapping("result.html")
	public String request(@RequestParam int questionID,@RequestParam int answerID, HttpSession session){
		userServise.setResult((Integer)session.getAttribute("userID"), questionID, answerID);
		Random random = new Random();
		int randomNumber = random.nextInt(5);

		if(session.getAttribute("answeredQuestions") == null){
			ArrayList<Integer> answeredQuestions = new ArrayList<Integer>(5);
			session.setAttribute("answeredQuestions", answeredQuestions);
			answeredQuestions.add(randomNumber);
			return "redirect:hello.html?id=" + randomNumber;
		} else if(((ArrayList)session.getAttribute("answeredQuestions")).size() == 5) {
			return ("redirect:index.jsp");
		}
		
		while(((ArrayList)session.getAttribute("answeredQuestions")).contains(randomNumber)) {
			randomNumber = random.nextInt(5);
		}
		((ArrayList)session.getAttribute("answeredQuestions")).add(randomNumber);
		return "redirect:hello.html?id=" + randomNumber;			
	}
	
	public ArrayList<Integer> randomList() {
		Random random = new Random();
		ArrayList<Integer> myArray = new ArrayList<Integer>();
		for (int i = 0; i < 4; i++) {
			int temp = random.nextInt(4);
			if (temp != 0) {
				if (!myArray.contains(temp)) {
					myArray.add(temp);
				}
			}
		}
	
	 return myArray;
	}

	
	
}
